﻿
using Castle.MonoRail.Framework;

namespace Castle.MonoRail.ViewComponents
{
    /// <summary>
    /// Very simple-minded ViewComponent to render the necessary Javascript
    /// for Google Analytics.
    /// </summary>
    /// <remarks>This is a line component which has no subsections and one required parameter.
    /// <list type="table">
    /// <listheader>
    /// <term>Parameter</term>
    /// <description>Description</description>
    /// </listheader>
    /// <item>
    /// <term>       id      </term>
    /// <description>The user account id provided by Google, for this website.  It's 
    /// generally in the form "UA-9999999-9".  (<b>required</b>, no default)
    /// </description>
    /// </item>
    /// </list>
    /// <b>Note:</b> This component works with the <see cref="JavascriptHelper"/> / 
    /// <see cref="InsertJavascriptComponent"/>, and requires that an InsertJavascript 
    /// ViewComponent appear somewhere in your output.
    /// </remarks>
    /// <example>
    /// <code>#component (GoogleAnalytics with "id=UA-00000000-0")
    /// </code>
    /// would render as:
    /// <code><![CDATA[
    /// <script type="text/javascript" src="http://www.google-analytics.com/urchin.js"></script>
    /// <script>
    /// _uacct = "UA-1066116-4"; urchinTracker();
    /// </script>
    /// ]]>
    /// </code>
    /// Note, if this component is placed within a view (rather than a layout), the line downloading 
    /// the javascript file may be move with similar line at the location of the 
    /// <see cref="InsertJavascriptComponent"/>.
    /// 
    /// </example>
    public class GoogleAnalyticsComponent : ViewComponentEx
    {

        /// <summary>
        /// Called by the framework so the component can
        /// render its content
        /// </summary>
        /// <remarks>Called by the framework.</remarks>
        public override void Render()
        {
            base.Render();
            string id = ComponentParams["id"] as string;
            if (id == null)
                throw new ViewComponentException("ID parameter must be given.");

            JavascriptHelper helper = new JavascriptHelper(Context, EngineContext, "GoogleAnalytics");
            helper.IncludeScriptFile(@"http://www.google-analytics.com/urchin.js");
            helper.IncludeScriptText("inline", @"_uacct = """ + id + @"""; urchinTracker();");
            CancelView();
        }
    }
}
